const fs = require('fs')
const path = require('path')
const { prompt } = require('enquirer')
const { stepOK, run } = require('./utils')
const rootDir = path.resolve(__dirname, '../')
const packagesDir = path.resolve(__dirname, '../packages')

/**
 * 搜集Git仓库
 */
function collectGitRepository() {
  let gitRepositories = [rootDir]
  const files = fs.readdirSync(packagesDir)
  files.forEach(shortname => {
    // 非目录的不处理
    if (!fs.statSync(path.join(packagesDir, shortname)).isDirectory()) return
    if (shortname.startsWith('@')) return
    gitRepositories.push(path.join(packagesDir, shortname))
  })
  return gitRepositories
}

/**
 * 在指定目录下拉取最新仓库代码
 * @param  workDirectory 命令执行目录
 */
async function pullRepository(workDirectory) {
  stepOK(`\n准备获取${workDirectory}最新代码...`)
  await run('git', ['pull'], { cwd: workDirectory, extendEnv: true })
  stepOK(`\n获取${workDirectory}最新代码成功...`)
}

/**
 * 在指定的目录下将本地仓库中的代码提交到远程仓库
 * @param  workDirectory 命令执行目录
 */
async function pushRepository(workDirectory) {
  stepOK(`\n提交到远程仓库：${workDirectory}...`)
  await run('git', ['push'], { cwd: workDirectory, extendEnv: true })
  stepOK(`\n提交到远程仓库：${workDirectory}成功...`)
}

/**
 * 获取用户输入的消息
 * @returns 用户输入的消息
 */
async function getCommitMessage() {
  const { message } = await prompt({
    type: 'input',
    name: 'message',
    message: '请输入本次提交的commit消息...'
  })
  if (!message) return getCommitMessage()
  return message
}

/**
 * 在指定的目录下将本地更新提交到本地仓库
 * @param  workDirectory 命令执行目录
 */
async function commitRepository(workDirectory) {
  let message = await getCommitMessage()

  stepOK(`\n添加到暂存区：${workDirectory}...`)
  await run('git', ['add', '-A'], { cwd: workDirectory, extendEnv: true })
  stepOK(`\n添加到暂存区：${workDirectory}成功...`)

  stepOK(`\n提交到本地仓库：${workDirectory}...`)
  await run('git', ['commit', '-m', message], { cwd: workDirectory, extendEnv: true })
  stepOK(`\n提交到本地仓库：${workDirectory}成功...`)
}

;(async function main() {
  const { choice } = await prompt({
    type: 'select',
    name: 'choice',
    message: '请选择你要执行的操作...',
    choices: [
      {
        name: 'pull-all',
        message: '拉取所有仓库的最新代码',
        value: 'pull-all'
      },
      {
        name: 'pull-km-wbp',
        message: '拉取样板工程(km-wbp)最新代码',
        value: 'pull-km-wbp'
      },
      {
        name: 'commit-km-wbp',
        message: '提交样板工程(km-wbp)本地工作区代码到本地仓库',
        value: 'commit-km-wbp'
      },
      {
        name: 'push-km-wbp',
        message: '推送样板工程(km-wbp)代码到远程仓库',
        value: 'push-km-wbp'
      },
      {
        name: 'pull-web',
        message: '拉取指定网站应用代码',
        value: 'pull-web'
      },
      {
        name: 'commit-web',
        message: '提交指定网站应用本地工作区代码到本地仓库',
        value: 'commit-web'
      },
      {
        name: 'push-web',
        message: '推送指定网站应用代码到远程仓库',
        value: 'push-web'
      }
    ]
  })
  console.log(choice)
  switch (choice) {
    /** 获取所有仓库的最新代码 */
    case 'pull-all':
      for (const gitRepository of collectGitRepository()) await pullRepository(gitRepository)
      break
    /** 获取样板工程最新代码 */
    case 'pull-km-wbp':
      pullRepository(rootDir)
      break
    case 'commit-km-wbp':
      commitRepository(rootDir)
      break
    /** 提交样板工程代码 */
    case 'push-km-wbp':
      pushRepository(rootDir)
      break
    case 'pull-web':
    case 'push-web':
      {
        const webRepositories = collectGitRepository().filter(gitRepository => gitRepository !== rootDir)
        const { webRepositoryChoice } = await prompt({
          type: 'select',
          name: 'webRepositoryChoice',
          message: '请选择你要拉取的网站应用的站点...',
          choices: webRepositories
        })
        if (choice === 'pull-web') {
          // 拉取远程代码到本地仓库
          pullRepository(webRepositoryChoice)
        } else if (choice === 'push-web') {
          // 推送本地仓库代码到远程
          pushRepository(webRepositoryChoice)
        } else {
          // 提交工作区代码到本地仓库
          commitRepository(webRepositoryChoice)
        }
      }
      break
    default:
      break
  }
})()
